package autotrade.data.dao;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import autotrade.data.structure.FxDatum;

public class FxDatumDao {
	public static void insert(PersistenceManager pm, FxDatum fx) {
		fx.setKey(_generateKey(fx.getPaircode(), fx.getDatetime().toString()));
		pm.makePersistent(fx);
	}
	public static void update(PersistenceManager pm, FxDatum fx) {
		FxDatum prev = selectByKey(pm, fx.getPaircode(), fx.getDatetime().toString());
		if(prev != null) {
			fx.setOpen(prev.getOpen());
			fx.setHigh( (fx.getHigh() > prev.getHigh()) ? fx.getHigh() : prev.getHigh() );
			fx.setLow( (fx.getLow() < prev.getLow()) ? fx.getLow() : prev.getLow());
			delete(pm, prev);
		}
		insert(pm, fx);
	}
	public static void delete(PersistenceManager pm, FxDatum fx) {
		pm.deletePersistent(fx);
	}
	
	public static FxDatum selectByKey(PersistenceManager pm, String paircode, String datetime) {
		try {
			return (FxDatum) pm.getObjectById(FxDatum.class, _generateKey(paircode, datetime));
		} catch(JDOObjectNotFoundException e) { System.out.println("not found"); }
		return null;
	}
	
	private static Key _generateKey(String paircode, String datetime) {
		String genkey = (paircode + datetime);
		Key key = KeyFactory.createKey(FxDatum.class.getSimpleName(), genkey);
		return key;
	}
}
